// components/search/search-cmp.js
const db = wx.cloud.database();

import {
	BookModel
} from "../../models/book.js";
import {
	KeywordModel
} from 'keyword.js'
import {
	paginationBev
} from '../behaviors/pagination.js'

let keyModel = new KeywordModel()

Component({
	/**
	 * 组件的属性列表
	 */
	behaviors: [paginationBev],
	properties: {
		more: {
			type: String,
			observer: '_loadMore'
		}
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		// start:0,
		// count:20,
		historyKeys: [],
		hotKeys: [],
		finished: false,
		q: '',
		loading: false,
		loadingCenter: false
	},

	attached: function () {
		this.setData({
			historyKeys: keyModel.getHistory()
		})
		keyModel.getHot((data) => {
			this.setData({
				hotKeys: data.hot
			})
		})
	},

	/**
	 * 组件的方法列表
	 * 
	 */
	methods: {
		_loadMore: async function () {
			// console.log("加载更多");
			if (!this.data.q) {
				return
			}
			let hasMore = this.hasMore()
			if (!hasMore) {
				return
			}
			this.setData({
				loading: true
			})

			var result = await BookModel.getHot();
			this.setMoreData(result.data)
			this.setData({
				loading: false
			})
			console.log(result);
			// http.request({
			// 	url: 'book/search?summary=1',
			// 	data: {
			// 		q: this.data.q,
			// 		start: this.getCurrentStart()
			// 	},
			// 	success: (data) => {
			// 		this.setMoreData(data.books)
			// 		this.setData({
			// 			loading: false
			// 		})
			// 	}
			// })


		},

		onCancel: function (event) {
			this.triggerEvent('cancel', {}, {})
		},

		onDelete: function (event) {
			this.setData({
				finished: false,
				empty: false,
				q: ''
			})
		},

		onConfirm: function (event) {
			// 首先切换状态，保持客户端流畅
			this.setData({
				finished: true,
				loadingCenter: true
			})

			this.initPagination()

			let q = event.detail.value || event.detail.text
			db.collection("book").where({
					bookName: db.RegExp({
						regexp: q,
					})
				}).get()
				.then(res => {
					if (res.data.length != 0) {
						keyModel.addToHistory(q)
						this.setData({
							empty:false
						})
					}
					this.setMoreData(res.data)
					this.setData({
						q: q,
						loadingCenter: false
					
					})
				})





		}
	}
})